import { useEffect, useState } from 'react';

import { FiX } from 'react-icons/fi';
import {
  ColumnDef,
  flexRender,
  getCoreRowModel,
  useReactTable,
  RowSelectionState,
} from '@tanstack/react-table';

import { cn } from '@/lib/utils';
import { Table, TableBody, TableCell, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';

interface DataTableProps<TData, TValue> {
  columns: ColumnDef<TData, TValue>[];
  data: TData[];
  onSelectedRowsChange?: (row: TData | null) => void;
  onDelete?: (row: TData) => void;
  resetTrigger?: number;
}

export function DataTable<TData, TValue>({
  columns,
  data,
  onSelectedRowsChange,
  onDelete,
  resetTrigger,
}: DataTableProps<TData, TValue>) {
  const [rowSelection, setRowSelection] = useState<RowSelectionState>({});

  // 定义删除按钮列 - 完全在当前文件内实现
  const deleteColumn: ColumnDef<TData> = {
    id: 'delete',
    size: 40,
    cell: ({ row }) => (
      <div className="flex justify-end w-full">
        <Button
          variant="ghost"
          onClick={(e) => {
            e.stopPropagation(); // 防止触发行选择
            if (row.getIsSelected()) {
              setRowSelection({});
            }
            if (onDelete) {
              onDelete(row.original); // 调用删除回调
            }
          }}
          className="h-6 w-6 p-0 rounded-full bg-gray-200 hover:bg-red-600"
          aria-label="删除行"
        >
          <FiX size={8} className={cn('h-3 w-3')} />
        </Button>
      </div>
    ),
  };

  // 合并原有列和删除列
  const tableColumns = [...columns, deleteColumn];

  const table = useReactTable({
    data,
    columns: tableColumns,
    enableRowSelection: true,
    enableMultiRowSelection: false,
    getCoreRowModel: getCoreRowModel(),
    state: {
      rowSelection,
    },
    onRowSelectionChange: setRowSelection,
  });

  useEffect(() => {
    if (resetTrigger) {
      setRowSelection({});
    }
  }, [resetTrigger]);

  // 监听选中行变化
  useEffect(() => {
    const seletedRowIds = Object.keys(rowSelection);

    if (seletedRowIds.length > 0) {
      const rowId = seletedRowIds[0];
      const row = table.getRow(rowId);

      if (row) {
        onSelectedRowsChange?.(row.original);
      }
    } else {
      onSelectedRowsChange?.(null);
    }
  }, [rowSelection, table]);

  return (
    <div className="rounded-md border overflow-auto">
      <Table>
        <TableBody>
          {table.getRowModel().rows?.length ? (
            table.getRowModel().rows.map((row) => (
              <TableRow
                key={row.id}
                data-state={row.getIsSelected() && 'selected'}
                className={`cursor-pointer h-10`}
                onClick={() => row.toggleSelected(true)}
              >
                {row.getVisibleCells().map((cell) => (
                  <TableCell
                    key={cell.id}
                    className={cn(
                      `${row.getIsSelected() ? 'bg-blue-50 dark:bg-blue-900/20' : ''} md:text-sm`
                    )}
                  >
                    {flexRender(cell.column.columnDef.cell, cell.getContext())}
                  </TableCell>
                ))}
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={columns.length + 1} className="h-24 text-center">
                No results.
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
    </div>
  );
}
